import { create } from 'zustand';

interface VoiceStore {
  voices: SpeechSynthesisVoice[];
  setVoices: (voices: SpeechSynthesisVoice[]) => void;
  isInitialized: boolean;
  setInitialized: (value: boolean) => void;
}

export const useVoiceStore = create<VoiceStore>((set) => ({
  voices: [],
  setVoices: (voices) => set({ voices }),
  isInitialized: false,
  setInitialized: (value) => set({ isInitialized: value }),
}));

export const initVoices = () => {
  const store = useVoiceStore.getState();
  const voices = window.speechSynthesis.getVoices();
  if (voices.length > 0) {
    store.setVoices(voices);
    store.setInitialized(true);
  }
};

// Initialize voices when the component mounts
if (typeof window !== 'undefined' && window.speechSynthesis) {
  // Try immediate initialization
  initVoices();
  
  // Also listen for the voiceschanged event
  window.speechSynthesis.onvoiceschanged = () => {
    initVoices();
  };
}

let currentSpeed = 1;
let currentUtterance: SpeechSynthesisUtterance | null = null;

export const setSpeed = (speed: number) => {
  // 只更新速度值，不影响当前正在播放的语音
  currentSpeed = speed;
};

export const getSpeed = () => currentSpeed;

export const playTextToSpeech = (text: string, accent: 'US' | 'UK') => {
  // 如果有语音正在播放，先停止它
  if (window.speechSynthesis.speaking) {
    window.speechSynthesis.cancel();
  }

  const utterance = new SpeechSynthesisUtterance(text);
  utterance.rate = currentSpeed;
  
  // 根据口音选择声音
  const voices = window.speechSynthesis.getVoices();
  const voice = voices.find(v => 
    accent === 'US' 
      ? v.lang === 'en-US' 
      : v.lang === 'en-GB'
  );
  
  if (voice) {
    utterance.voice = voice;
  }
  
  // 保存当前播放的utterance引用
  currentUtterance = utterance;
  
  window.speechSynthesis.speak(utterance);
};

export const getAvailableVoices = (accent: 'US' | 'UK'): boolean => {
  const { voices } = useVoiceStore.getState();
  const lang = accent === 'US' ? 'en-US' : 'en-GB';
  return voices.some(voice => voice.lang.startsWith(lang));
};